package com.raisecom.control.toolaction;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.Enumeration;

import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JRadioButton;

import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;

public class ToolRadioActionListener implements ActionListener{
	private Element rootElement = null;
	private ButtonGroup buttonGroup = null;
	

	public ToolRadioActionListener(Element rootElement, ButtonGroup buttonGroup) {
		this.rootElement = rootElement;
		this.buttonGroup = buttonGroup;
		
	}

	public void actionPerformed(ActionEvent actionevent) {
		Enumeration<AbstractButton> elements = buttonGroup.getElements();
		while(elements.hasMoreElements()){
			JRadioButton nextRadioBtn = (JRadioButton) elements.nextElement();
			if(nextRadioBtn.isSelected()){
				String actionCommand = nextRadioBtn.getActionCommand();
				try {
					Element jRadioButtonEle = (Element) XPath.selectSingleNode(rootElement, "/buttons/tool/button[@actioncommand='"+actionCommand+"']");
					String selectedimage = jRadioButtonEle.getAttributeValue("selectedimage");
					URL url = this.getClass().getResource(selectedimage);
					nextRadioBtn.setIcon(new ImageIcon(url.getPath()));
					
				} catch (JDOMException e) {
					e.printStackTrace();
				}
				
				
			}else{
				String actionCommand = nextRadioBtn.getActionCommand();
				try {
					Element jRadioButtonEle = (Element) XPath.selectSingleNode(rootElement, "/buttons/tool/button[@actioncommand='"+actionCommand+"']");
					String initimage = jRadioButtonEle.getAttributeValue("initimage");
					URL url = this.getClass().getResource(initimage);
					nextRadioBtn.setIcon(new ImageIcon(url.getPath()));
					
				} catch (JDOMException e) {
					e.printStackTrace();
				}
			}
		}
		
	}

}
